%This script produces the adjustment vectors for the share matrices used to
%compute the IVs in estimation
%Corresponding author: Rodrigo Adao
%Date: 09/11/2024
%Input: model_data_fgkk.mat

%% Parameters for estimation

clear;
close all;

%Define vector of varieties in our sample
trade_target = 0.9;

%set lacal paths
function_path = "..\Functions\";
addpath(function_path,'-frozen');
set_local_paths;
    
%% Import data

%estimation parameters
test_cluster = 1;   

%Run preliminary steps for estimation
estimation_preliminary_steps;
         
%% Shares

%Compute MC times share_sharep
tic

    shareMOD_dW_T = shareMOD_dW'; 
    share_sharep = zeros(Nobs, Nobs);
    MC_share_sharep = zeros(Nobs,Nobs);
    
    MCterm3 = eye(Nobs) ;
    
    Nobs
   parfor s=1:Nobs 
        auxT = shareMOD_dW_T(:,s);
        aux0 = shareMOD_dW*auxT;
        share_sharep(:,s) = aux0;
   
        %controls 
        aux1 = MC_term1(:,s);
        MC_term2=C*aux1;
        aux2= MCterm3(:,s)  - MC_term2;
        MC_share_sharep(:,s) = aux2.*aux0;
   end
toc

%Compute welfare adjustment vector
tic
    %Weighted
    omega_share = adjGE_const*(ww_dW.*shareMOD_dWbar);
    adjGE_wMC = MC_share_sharep\omega_share;
toc    

%output to save
save(save_share_path + "estimation_shares_t" + trade_target + ".mat", 'adjGE_wMC', 'trade_target')

